package com.david.rocket.stream;

import com.david.rocket.common.Const;
import com.david.rocket.dao.GoodsRepository;
import com.david.rocket.dao.OrderRepository;
import com.david.rocket.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

import static com.david.rocket.common.Const.TOPIC_ORDER_CHECK;

@Slf4j
@Component
@RocketMQMessageListener(topic = TOPIC_ORDER_CHECK, consumerGroup = "group-check")
class OrderCheckConsumer implements RocketMQListener<String> {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private GoodsRepository goodsRepository;

//    @Transactional(rollbackFor = Exception.class)
    @Override
    public void onMessage(String payload) {
        String orderId = payload;
        log.info("orderId ===>" + orderId);
        Optional<OrderEntity> o = orderRepository.findOrderEntitiesByOrderId(orderId);
        if (o.isPresent()) {
            OrderEntity orderEntity = o.get();
            //还在付款中取消订单恢复库存
            if (Const.OrderStatue.valueOf(orderEntity.getStatus()) == Const.OrderStatue.paying) {
                orderEntity.setStatus(Const.OrderStatue.canceled.name());
                orderRepository.save(orderEntity);
                log.info("cancel order ===>" + orderId);
                Long goodsId = orderEntity.getGoodsId();
                goodsRepository.increaseStock(goodsId);
                log.info("increase stock===>" + goodsId);
            }
        }
    }
}
